<%
const { endpoints, name: moduleName } = data;

function renderField(field) {
  // 检查是否存在 required 属性
  const isRequired = field.required;
  const fieldType = field.type; // 直接使用 field.type，不再进行类型判断

  return isRequired ? fieldType : `Option<${fieldType}>`;
}

function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
%>

use salvo::oapi::{ToParameters, ToSchema};
use serde::{Deserialize, Serialize};
<%_ /* 只在需要用到 Validate 的地方引入 */ _%>
use validator::Validate;

<%_ endpoints.forEach(endpoint => { _%>
<%_ if (endpoint.structName.response) { _%>
#[derive(Serialize, Deserialize, Clone, Debug, Default, ToSchema)]
#[serde(rename_all = "camelCase")]
#[serde(default)]
pub struct <%= `${capitalizeFirstLetter(endpoint.structName.response)}` %> {
  <%_ Object.keys(endpoint.response[0]).forEach(field => { _%>
    pub <%= field %>: <%= renderField(endpoint.response[0][field]) %>, 
  <%_ }) _%>
}
<%_ } _%>

<%_ if (endpoint.structName.params) { _%>
<%_ if (endpoint.method === 'GET') { _%>
#[derive(Deserialize, Clone, Debug, Default, ToParameters, Validate)]
#[salvo(parameters(default_parameter_in = Query))]
<%_ } else { _%>
#[derive(Serialize, Deserialize, Clone, Debug, Default, ToSchema, Validate)]
#[serde(rename_all = "camelCase")]
#[serde(default)]
<%_ } _%>
pub struct <%= `${capitalizeFirstLetter(endpoint.structName.params)}` %> {
  <%_ Object.keys(endpoint.params[0]).forEach(field => { _%>
    <%_ if (endpoint.params[0][field].required) { _%>
    #[validate(length(min = 1, message = "<%= endpoint.params[0][field].message || field + '不得为空' %>"))]
    pub <%= field %>: <%= renderField(endpoint.params[0][field]) %>, 
    <%_ } else { _%>
    pub <%= field %>: <%= renderField(endpoint.params[0][field]) %>, 
    <%_ } _%>
  <%_ }) _%>
}
<%_ } _%>

<%_ if (endpoint.structName.body) { _%>
#[derive(Serialize, Deserialize, Clone, Debug, Default, ToSchema, Validate)]
#[serde(rename_all = "camelCase")]
#[serde(default)]
pub struct <%= `${capitalizeFirstLetter(endpoint.structName.body)}` %> {
  <%_ Object.keys(endpoint.body[0]).forEach(field => { _%>
    <%_ if (endpoint.body[0][field].required) { _%>
    #[validate(length(min = 1, message = "<%= endpoint.body[0][field].message || field + '不得为空' %>"))]
    pub <%= field %>: <%= renderField(endpoint.body[0][field]) %>, 
    <%_ } else { _%>
    pub <%= field %>: <%= renderField(endpoint.body[0][field]) %>, 
    <%_ } _%>
  <%_ }) _%>
}
<%_ } _%>
<%_ }) _%>